package org.example.cake.controller;
import afu.org.checkerframework.checker.units.qual.A;
import com.github.pagehelper.PageInfo;
import org.example.cake.common.Rep;
import org.example.cake.entity.Discuss;
import org.example.cake.entity.Discussimg;
import org.example.cake.mapper.DiscussMapper;
import org.example.cake.mapper.DiscussimgMapper;
import org.example.cake.mapper.OrdercakeMapper;
import org.example.cake.service.DiscussService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static java.time.LocalTime.now;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/discuss")
public class DiscussController {

    @Autowired
    private DiscussService discussService;
    /**
     * 前端方法：根据蛋糕id查询有关评论
     * @param cakeid 蛋糕id
     * @author 李丽君
     * @Date 2025-07-25
     * @return 评论实体
     */
    @GetMapping("/selectByCakeId")
    public Rep selectByCakeId(@RequestParam("cakeid") Integer cakeid){
        List<Discuss> selectByCakeId = this.discussService.selectByCakeId(cakeid);
        return new Rep().addData("selectByCakeId", selectByCakeId);
    }

    @Autowired
    private DiscussMapper discussMapper;
    @Autowired
    private OrdercakeMapper ordercakeMapper;

    @PostMapping("/insertDiscuss")
    @Transactional(rollbackFor = Exception.class)
    public Rep insertDiscuss(@RequestBody Map<String,String> map) {
        String orderid = map.get("orderid");
        String discusscontent = map.get("discusscontent");
        Rep rep = new Rep();
        try {
            System.out.println("获取到的orderid = " + orderid);
            // 1. 参数校验
            if (orderid == null) {
                return rep.addData("添加评论状态", "订单ID不能为空");
            }

            if (discusscontent == null) {
                return rep.addData("添加评论状态", "评论内容不能为空");
            }

//            try {
//                orderId = Integer.parseInt(orderid);
//            } catch (NumberFormatException e) {
//                return rep.addData("添加评论状态", "订单ID格式错误");
//            }

            // 2. 检查是否已存在评论（幂等性处理）
//            if (!discussMapper.selectByOrderId(Integer.valueOf(orderid))) {
//                return rep.addData("添加评论状态", "该订单已评论，请勿重复提交");
//            }

            // 3. 创建并保存评论
            Discuss discuss = new Discuss();
            discuss.setDiscusscontent(discusscontent);
            discuss.setOrderid(Integer.valueOf(orderid));
            discussMapper.insertDiscuss(discuss);

            int generatedDiscussId = discuss.getDiscussid();
            System.out.println("生成的评论ID: " + generatedDiscussId);

            // 4. 更新订单评论状态
            ordercakeMapper.updateOrderDiscussIf(Integer.valueOf(orderid), 1);

            return rep.addData("添加评论状态", "新增评论成功").addData("discussid", generatedDiscussId);

        } catch (Exception e) {
            return rep.addData("添加评论状态", "新增评论失败: " + e.getMessage());
        }
    }


    /**
     * 查询所有评论相关的信息
     * @author luojiangjin
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/selectAllDis")
    public Rep getAllDiscussWithDetails(
            @RequestParam("page") Integer page,
            @RequestParam("pageSize") Integer pageSize) {
        PageInfo<Discuss> pageInfo = discussService.getAllDiscussWithDetails(page, pageSize);
        return new Rep().addData("discussPageInfo", pageInfo);
    }

    /**
     * 根据评论内容，用户名称，蛋糕名字模糊查询所有评论相关的信息
     * @author luojiangjin
     * @param page 当前页码
     * @param pageSize 每页条数
     * @param keyword 搜索关键词
     * @return
     */
    @GetMapping("/selectAllDisByKey")
    public Rep getDiscussList(
            @RequestParam("page") Integer page,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        PageInfo<Discuss> pageInfo = discussService.getDiscussList(page, pageSize, keyword);
        return new Rep().addData("discussPageInfo", pageInfo);
    }

    /**
     * 删除评论
     * @author luojiangjin
     * @param discussId 评论id
     * @return 统一响应格式
     */
    @DeleteMapping("/{discussId}")
    public ResponseEntity<Map<String, Object>> deleteDiscuss(@PathVariable Integer discussId) {
        // 1. 参数验证
        if (discussId == null || discussId <= 0) {
            return ResponseEntity.badRequest().body(Map.of(
                    "code", 400,
                    "message", "评论ID必须为正整数"
            ));
        }

        // 2. 执行业务逻辑
        try {
            boolean result = discussService.deleteDiscuss(discussId);
            if (result) {
                return ResponseEntity.ok(Map.of(
                        "code", 200,
                        "message", "删除成功"
                ));
            }
            return ResponseEntity.status(500).body(Map.of(
                    "code", 500,
                    "message", "删除失败"
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                    "code", 500,
                    "message", "删除失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 查询评论图片
     * @author luojiangjin
     * @param discussId 评论id
     * @return 统一响应格式
     */
    @GetMapping("/images/{discussId}")
    public Rep getDiscussImages(@PathVariable Integer discussId) {
        List<String> images = discussService.getDiscussImages(discussId);
        return new Rep().addData("images", images);
    }



}
